# r, w, r+ 读写
# 所有的写，都是覆盖，修改不了源文件，可以新建一个临时文件


import shutil
import os
def file_replace():
    src_file = r"D:\PycharmPythonProject\project1110\filetest\test2.txt"

    # 创建临时文件
    tmp_file = r"D:\PycharmPythonProject\project1110\filetest\test2_tmp.txt"
    tmp_obj = open(tmp_file, mode="w")
    with open(src_file, mode="r") as src_obj:
        for line in src_obj:
            if "shell" in line:
                new_line = line.replace("shell", "python")
                tmp_obj.write(new_line)
            else:
                tmp_obj.write(line)
    tmp_obj.close()

    shutil.copy(tmp_file, src_file)
    os.remove(tmp_file)
    print("文件替换成功")
if __name__ == '__main__':
    file_replace()

